﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Diagnostics;
using android_charge.Properties;
using System.Text.RegularExpressions;
using System.Text;
using System.Runtime.CompilerServices;
using android_charge.Utils;
using android_charge.compent;

namespace android_charge
{
    public class Amazon : Form
    {
        public int x { get; set; } = 0;
        public int y { get; set; } = 0;

        public int offsetX = 50;

        public int offsetY = 30;

        public string devices_id;

        private static string serverRegex = @"server:\s*(\S+),";

        private static string portRegex = @"port:\s*(\d+)";

        public string server;

        public string port;

        public string region;

        public string link;


        public string gaid;

        public string zip;

        public Ip ip1;

        public string[] labelMap;

        public static HttpClient client = new HttpClient(new HttpClientHandler
        {
            Proxy = null,
            UseProxy = false
        });

        public MoveListener listener;

        public Content content1;

        public Amazon()
        {

            ip1 = new compent.Ip();

            ip1.BackColor = Color.Transparent;
            ip1.Location = new Point(0, -4);
            ip1.Name = "ip1";
            ip1.Size = new Size(93, 116);
            ip1.TabIndex = 30;
            Controls.Add(ip1);
            content1 = new compent.Content();

            content1.Location = new Point(4, 100);
            content1.Name = "content1";
            content1.Size = new Size(88, 254);
            content1.TabIndex = 31;
            Controls.Add(content1);
        }

        public virtual void OnHandleCreated(object sender, EventArgs e)
        {
            listener.UpdateStatus();
            listener.UpdateLocation();
        }

        public void send_curl(bool retry=false)
        {
            string exit_curl = adb_shell_cmd("ls /data/curl");
            if (exit_curl.Contains("No"))
            {
                try
                {
                    // 创建临时文件
                    string tempFilePath = Path.GetTempFileName();
                    File.WriteAllBytes(tempFilePath, Resources.curl);
                    // 构建ADB命令
                    string res = adb_cmd($"push \"{tempFilePath}\" /data/curl");

                    // 删除临时文件
                    File.Delete(tempFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
                //修改权限
                var r = adb_shell_cmd("chmod -R 777 /data/curl");
                if (!retry && r.Contains("No"))
                {
                    // 没发成功重试一次
                    send_curl(true);
                }
            }

        }

        public virtual void init()
        {

            // 查看是否存在curl            
            string exit_curl = adb_shell_cmd("ls /data/curl");
            if (exit_curl.Contains("No"))
            {
                send_curl();
            }
            // 处理clash_config
            try
            {
                clash_config();
            }
            catch (Exception ex)
            {
                Thread.Sleep(3000);
                clash_config();
            }
            queryLink();
            region = adb_shell_cmd("\"cat /data/data/com.ghb.GPTools/AllParamText.txt | awk -F'country_code\\\":\\\"' '{print $2}' | awk -F'\\\"' '{print $1}'\"").Trim();
            init_callback();
        }

        public void queryLink()
        {
            var res = adb_shell_cmd("\"cat /data/data/com.ghb.GPTools/DDJText.txt | awk -F'offer_id=' '{print $2}' | awk -F'&' '{print $1}'\"").Trim();
            if (!res.Contains("cat"))
            {
                link = res;
            }
        }

        public void clash_config()
        {
            
            // 查看clash配置
            string clash_config = adb_shell_cmd("cat /data/data/com.github.kr328.clash/files/processing/config.yaml");
            if (clash_config.Contains("cat"))
            {
                // 新clash 包名不同
                clash_config = adb_shell_cmd("cat /data/data/com.github.metacubex.clash.meta/files/processing/config.yaml");
            }
            var ser = Regex.Match(clash_config, serverRegex);
            var p = Regex.Matches(clash_config, portRegex);
            if (ser.Success)
            {
                server = ser.Groups[1].Value;
            }

            if (p.Count>2&&p[2].Success)
            {
                port = p[2].Groups[1].Value;
            }

        }


        public void goLink(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                switchClashMode(ClashMode.RULE);
            });
            gaid = getGaid();
            if (string.IsNullOrEmpty(gaid))
            {
                MessageBox.Show("未查询到gaid");
                return;
            }
            // 过链接
            string ph_name = GenerateRandomString(9);
            openUrl($"http://link.51wmsy.com/clicks?offer_id={link}&type=1&aid={gaid}&click_id={gaid}&ph_name={ph_name}");
        }

        public virtual void ip_info()
        {
            ip1.checkIp();
        }
        public string adb_cmd(string c)
        {
            using (Process process = new Process())
            {
                var arg = $"-s {devices_id} {c}";
                process.StartInfo = new ProcessStartInfo("adb")
                {
                    Arguments = arg,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                process.Start();
                string output = process.StandardOutput.ReadToEnd();
                string error = process.StandardError.ReadToEnd();

                process.WaitForExit();
                if (!string.IsNullOrEmpty(error))
                {
                    return error;
                }
                return output;
            }

        }

        public string adb_shell_cmd(string c)
        {
            return adb_cmd($"shell {c}");
        }

        /**
         * 数字代表换行几次
         */
        public async void batch_adb_input(params object[] inputs)
        {


            StringBuilder cmd = new StringBuilder();
            for (int i = 0; i < inputs.Length; i++)
            {
                var item = inputs[i];
                if (item is string)
                {
                    cmd.Append($"adb  -s {devices_id} shell input text '{(string)item}'");
                    if (i < inputs.Length - 1)
                    {
                        cmd.Append(" && ");
                    }
                }
                else if (item is int)
                {
                    for (int j = 0; j < (int)item; j++)
                    {
                        cmd.Append($"adb  -s {devices_id} shell input keyevent KEYCODE_TAB");
                        if (i < inputs.Length - 1 || j < (int)item - 1)
                        {
                            cmd.Append(" && ");
                        }
                    }
                }

            }

            using (Process process = new Process())
            {
                process.StartInfo = new ProcessStartInfo
                {
                    FileName = "cmd.exe",
                    Arguments = $"/c {cmd}",
                    RedirectStandardOutput = true,
                    UseShellExecute = false,
                    CreateNoWindow = true
                };
                process.Start();
                Task processTask = Task.Run(() => process.WaitForExit());
                if (await Task.WhenAny(processTask, Task.Delay(5000)) != processTask)
                {
                    process.Kill();
                    this.Invoke(() => { MessageBox.Show("填卡超时"); });
                }
            }
        }


        public virtual JObject Check_IP(bool isRetry = false)
        {
            /* 
             {"status":"success","country":"United States","countryCode":"US","region":"AL","regionName":"Alabama","city":"Maylene","zip":"35114","lat":33.2346,"lon":-86.8703,"timezone":"America/Chicago","isp":"AT\u0026T Services, Inc.","org":"AT\u0026T Corp","as":"AS7018 AT\u0026T Services, Inc.","query":"99.104.133.54"}
             */
            string ipInfo = adb_shell_cmd("/data/curl -s http://ip-api.com/json");
            try
            {
                Debug.WriteLine($"{devices_id} 查询ip--- 结果{ipInfo}");
                var obj = JsonConvert.DeserializeObject<JObject>(ipInfo);

                if (obj != null && obj["status"] != null && obj["status"].ToString() == "success")
                {
                    return obj;
                }
                if (!isRetry)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        var o = Check_IP(true);
                        if (o != null && o["status"] != null && o["status"].ToString() == "success")
                        {
                            return o;
                        }
                    }
                }
                return new JObject();

            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
                if (!isRetry)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        var o = Check_IP(true);
                        if (o != null && o["status"] != null && o["status"].ToString() == "success")
                        {
                            return o;
                        }
                    }
                }
                return new JObject();
            }
        }

        public virtual void init_callback()
        {

        }

        public async void changeIp(Ip ip = null)
        {
            if (string.IsNullOrEmpty(port) || string.IsNullOrEmpty(server))
            {
                MessageBox.Show("端口或服务器地址为空");
                return;
            }
            try
            {
                string res;
                if (server == "119.12.164.151")
                {
                    res = await client.GetStringAsync($"http://{server}:8090/oxy/updater?ip=119.12.164.151&port={port}&country={region}");
                }
                else
                {
                    res = await client.GetStringAsync($"http://{server}/ipidealabs.php?country={region}&port={port}");
                }
                if (!res.ToLower().Contains("success"))
                {
                    MessageBox.Show(res);
                }
                ip.checkIp();
                if (string.IsNullOrEmpty(zip) && content1.currAccount != null)
                {
                    content1.currAccount["zip"] = zip;
                }
            }
            catch (Exception ex)
            {
                // Debug.WriteLine("换ip异常");
                MessageBox.Show(ex.Message);
            }

        }


        public void Send(string text)
        {
            adb_shell_cmd($"input text '{text}'");
        }


        public string getCurrPackageName()
        {
            return adb_shell_cmd("\"dumpsys activity activities | grep 'mResumedActivity' | awk '{print $4}' | cut -d '/' -f 1\"").Trim();
        }


        public void batch_adb(params string[] args)
        {
            StringBuilder cmd = new StringBuilder();
            for (int i = 0; i < args.Length; i++)
            {
                var item = args[i];

                cmd.Append($"adb  -s {devices_id} shell \"{item}\"");
                if (i < args.Length - 1)
                {
                    cmd.Append(" && ");
                }

            }

            ProcessStartInfo psi = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                Arguments = $"/c {cmd}",
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            Process process = Process.Start(psi);
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
        }


        public virtual void closeCallBack()
        {
            amazonStatus(1);
        }

        public void active(Action action)
        {
            try
            {
                gaid = getGaid();
                // 查加钱
                var obj = JsonConvert.DeserializeObject<JObject>(client.GetStringAsync($"http://hy.51wmsy.com/api/run_lc?bid=com.amazon.mp3&aid={gaid}").Result);
                var sta = obj["status"].ToString();
                if (sta.Equals("1"))
                {
                    this.Invoke(() =>
                    {
                        MessageBox.Show("已加钱");
                        if (content1.currAccount["amzonAcc"] == null)
                        {
                            // 加载亚马逊账号
                            action();
                            // jpAmazonAcc(false);
                        }
                    });
                }
                else
                {
                    this.Invoke(() =>
                    {
                        MessageBox.Show("未加钱");
                    });
                }
            }
            catch (Exception ex)
            {
                this.Invoke(() =>

                {
                    MessageBox.Show("异常请重试");
                });
            }

        }

        public virtual void setcurrAccount(JObject account, string cuLink = "")
        {
            content1.setcurrAccount(account, cuLink);
        }

        public void importClashConfig()
        {
            getPort();
            if (!string.IsNullOrEmpty(port))
            {
                adb_shell_cmd($"am start -a android.intent.action.VIEW -d 'clash://install-config?url=http://47.96.125.116:1020/daili?dk={port}%26dl={Main.vpn}'");
            }
            importClashConfigCallBack();
        }

        public virtual void importClashConfigCallBack() { }

        public void amazonStatus(int status, string cmp = "54117")
        {
           content1.amazonStatus(status, cmp);
        }

        

        public void openUrl(string url)
        {
            adb_shell_cmd($"am start -a android.intent.action.VIEW -d '{url}' -n com.chrome.dev/com.google.android.apps.chrome.Main");
        }

        public string getGaid()
        {
            //  link = adb_shell_cmd("\"cat /data/data/com.ghb.GPTools/DDJText.txt | awk -F'offer_id=' '{print $2}' | awk -F'&' '{print $1}'\"").Trim();

            return adb_shell_cmd("\"cat /data/data/com.google.android.gms/shared_prefs/adid_settings.xml | awk -F'[<>]' '/<string name=\\\"adid_key\\\">/ {{print $3}}'\"").Trim();
        }


        public void reStart(object sender, EventArgs e)
        {
            // 获取当前包名
            string pack = getCurrPackageName();
            batch_adb($"am force-stop {pack}", $"monkey -p {pack} -c android.intent.category.LAUNCHER 1");
        }


        public static string GenerateRandomString(int length)
        {
            const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            StringBuilder result = new StringBuilder(length);
            Random random = new Random();

            for (int i = 0; i < length; i++)
            {
                result.Append(chars[random.Next(chars.Length)]);
            }

            return result.ToString();
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void getPort()
        {
            if (string.IsNullOrEmpty(port))
            {
                if (Main.config["ports"] == null)
                {
                    Main.config.Add("ports", new JObject());
                }
                var imei = Main.config["ports"][devices_id]?.ToString();
                if (string.IsNullOrEmpty(imei))
                {
                    imei = GenerateRandomString(9);
                    Main.config["ports"][devices_id] = imei;
                }
                try
                {
                    port = client.GetStringAsync($"http://47.96.125.116:1020/port?api=getport&ip={Main.vpn}&imei={imei}").Result;
                }
                catch
                {

                }
            }

        }


        /*private void InitializeComponent()
        {
            SuspendLayout();
            // 
            // SideTool
            // 
            ClientSize = new Size(152, 253);
            Name = "SideTool";
            ResumeLayout(false);
        }*/

        public void switchClashMode(ClashMode mode)
        {


            if (port == null)
            {
                MessageBox.Show("全局切换失败 端口为空");
                return;
            }
            if (mode.Equals(ClashMode.GLOBAL))
            {
                // 开全局
                string setGlobal = "/data/curl -s -X PATCH http://localhost:9090/configs -d '{\\\"mode\\\": \\\"global\\\"}' -H 'Content-Type: application/json'";
                string setProxy = $"/data/curl -s -X PUT http://localhost:9090/proxies/GLOBAL -d '{{\\\"name\\\": \\\"{Main.vpn}_{port}\\\"}}' -H 'Content-Type: application/json'";
                batch_adb(setGlobal, setProxy);
            }
            else
            {
                // 关全局
                adb_shell_cmd("/data/curl -X PATCH http://localhost:9090/configs  -d '{\\\"mode\\\": \\\"rule\\\"}' -H 'Content-Type: application/json'");
            }
        }
    }
    public enum ClashMode
    {
        GLOBAL, RULE
    }
}
